package userFileModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"KumquatDrivesServices/utils"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"time"
)

type getPreviewIdRequest struct {
	FileId model.SnowflakeIdType `form:"fileId" binding:"required"`
}

func (UserFileModuleApi) GetPreviewId(c *gin.Context) {
	var req getPreviewIdRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		logrus.Errorf("ShouldBindQuery err:%v", err)
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	userId := utils.GetUserId(c)
	if userId == 0 {
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}

	var fileModel model.FileModel
	query := global.DB.Where("id=? and user_id=? and del_flag=? and is_folder=?", req.FileId, userId, enums.Normal, enums.File)
	if err := query.First(&fileModel).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			res.FailWithCode(res.PARAM_ERR, c)
			return
		}
		logrus.Errorf("query.First err:%v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if fileModel.IsFolder == enums.Folder {
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	previewId := fmt.Sprint(utils.RandomString(8), time.Now().Unix())
	if err := cachePreviewIdOfFileInfo(previewId, fileModel.FilePath); err != nil {
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	res.OkWithData(map[string]string{"previewId": previewId}, c)
}
